package Utils.db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * C3P0工具类
 *
 * @author d11yu
 */
public class C3P0Utils {
    private static ComboPooledDataSource cpds = null;
    private static C3P0Utils instance = null;

    /**
     * 构造函数
     *
     */
    private C3P0Utils() {
        cpds = new ComboPooledDataSource();
    }

    /**
     * 构造函数
     *
     * @param configName 配置方案的名称
     */
    private C3P0Utils(String configName) {
        cpds = new ComboPooledDataSource(configName);
    }

    /**
     * 获取实例，选择默认配置（default-config）
     *
     * @return
     */
    public static C3P0Utils getInstance() {
        if (instance == null) {
            instance = new C3P0Utils();
        }
        return instance;
    }

    /**
     * 获取实例
     *
     * @param configName 配置方案的名称
     * @return
     */
    public static C3P0Utils getInstance(String configName) {
        if (instance == null) {
            instance = new C3P0Utils(configName);
        }
        return instance;
    }

    /**
     * 根据配置文件中的configName获取C3P0的ComboPooledDataSource
     *
     * @return
     */
    public ComboPooledDataSource getCdps() {
        return cpds;
    }

    /**
     * 获取SQL Connection
     *
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return cpds.getConnection();
    }
}
